package camid.services.cloudmanager;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import camid.services.nameservice.EntityMetadata;

public class AdaptiveLoadBalancingStrategy2 implements LoadBalancingStrategy {

	private IClusterManagerRegistry clusterRegistry;
	
	private int counter;
	
	public AdaptiveLoadBalancingStrategy2(IClusterManagerRegistry clusterRegistry) {
		this.clusterRegistry = clusterRegistry;
		this.counter = 0;
	}
	
	@Override
	public String selectNode(EntityMetadata metadata, List<String> nodeIds) {
		Map<String,Double> costMap = this.clusterRegistry.getCostMap(nodeIds);
		
		double leastCost = Double.MAX_VALUE; 
		String leastLoadedNode = null;
		
		String nextNode = null;
		double nextNodeCost = 0.0;
		
		int pos = counter % costMap.size();
		counter = pos + 1;
		
		int i = 0;
		for (Entry<String,Double> entry : costMap.entrySet()) {
			String nodeId = entry.getKey();
			double cost = entry.getValue();
			if (cost < leastCost) {
				leastCost = cost;
				leastLoadedNode = nodeId;
			}
			
			if ( i == pos ) {
				nextNodeCost = cost;
				nextNode = nodeId;
			}
			i++;
		}
		
		String selectedNode = null;
		
		if(nextNodeCost < 0.7) {
			selectedNode = nextNode;
		} else {
			selectedNode = leastLoadedNode;
		}
		
		return selectedNode;
	}

	@Override
	public String reselectNode(EntityMetadata metadata, List<String> nodeIds,
			String oldNodeId) {
		
		String leastLoadedNodeId = null;
		double leastLoadedNodeCost = Double.MAX_VALUE;
		
		Map<String,Double> costMap = this.clusterRegistry.getCostMap(nodeIds);
		
		if(costMap.containsKey(oldNodeId)) {
		
			for (Entry<String,Double> entry : costMap.entrySet()) {
				String nodeId = entry.getKey();
				double cost = entry.getValue();
				if (cost < leastLoadedNodeCost) {
					leastLoadedNodeCost = cost;
					leastLoadedNodeId = nodeId;
				}
			}
			
			double oldNodeCost = costMap.get(oldNodeId);
			if((oldNodeCost - leastLoadedNodeCost) >= 0.2) {
				return leastLoadedNodeId;
			}
			
		}
		
		return oldNodeId;
	}
	
	

}
